<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
	
class SendCodeController extends Controller
{
 	public function __construct()
    {
        $this->middleware('guest');
    }	

    // 手机发送
    public function sendPhone(Request $request) 
    {	    	
    	$RecNum = $request->input("username");
    	$type = $request->input('type');
    	$num = $this->random(6);
		$host = "http://sms.market.alicloudapi.com";
	    $path = "/singleSendSms";
	    $method = "GET";
	    $appcode = "98c9883732b24430bea008dbeaeb9b75";
	    $SignName = "小豆";
	    $TemplateCode = "SMS_71166239";
	    $ParamString = urlencode('{"code": "'.$num.'"}');	   
	    $headers = array();
	    array_push($headers, "Authorization:APPCODE " . $appcode);
	    $querys = "ParamString=". $ParamString ."&RecNum=".$RecNum."&SignName=".urlencode($SignName)."&TemplateCode=".urlencode($TemplateCode);
	    $bodys = "";
	    $url = $host . $path . "?" . $querys;

	    $curl = curl_init();
	    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
	    curl_setopt($curl, CURLOPT_URL, $url);
	    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	    curl_setopt($curl, CURLOPT_FAILONERROR, false);
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($curl, CURLOPT_HEADER, true);
	    if (1 == strpos("$".$host, "https://"))
	    {
	        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	    }
		$result = curl_exec($curl);

		if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == 200) {
		    // $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
		    // $header = substr($result, 0, $headerSize);
		    // $body = substr($result, $headerSize);


		    session([$type => $num]);
		    $message['result'] = 'success';
		    return $message;
		}else {
			$message['result'] = 'error';
			return $message;
		}
    }
	

    private function random($length)
	{
		$pattern = '1234567890'; //字符池
		$key = "";
		for($i=0; $i<$length; $i++)
		{
			$key .= rand(0, 9); //生成php随机数
		}
		return $key;
	}
}